// Copyright (c) 2015 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.

#ifndef CEF_TESTS_CEFCLIENT_BROWSER_DOWNLOAD_SERVICE_H_
#define CEF_TESTS_CEFCLIENT_BROWSER_DOWNLOAD_SERVICE_H_
#pragma once

#include <string>
#include "include/cef_base.h"
#include "include/cef_thread.h"
#include "include/cef_client.h"
#include "include/base/cef_ref_counted.h"
#include "include/internal/cef_types_wrappers.h"
#include "tests/cefclient/others/curl.h"
#include "tests/cefclient/browser/protocol.h"
#include <list>
#include <mutex>
 

namespace client {

class PreTask : public CefTask {
	public:
		PreTask(CefString &url);
		~PreTask();
		void Execute() override;
	private:
		void Taskfailed();

	private:
		long filesize;
		int progress;
		CefString remoteurl;
		CefString paperid;
		CefString filename;
		CefString  remotedir;
		IMPLEMENT_REFCOUNTING(PreTask);
	};
 
class DVideoTask : public CefTask {
	public:
		DVideoTask(CefString &url );
		~DVideoTask();
		void Execute() override;
private:
	  void Taskfailed();
 
	private: 
		long filesize;
		int progress;
		CefString remoteurl;
		CefString paperid;
		CefString filename;
		CefString  remotedir;
		IMPLEMENT_REFCOUNTING(DVideoTask);
};

// Used to store user info and login token. The methods of this
// class are thread-safe unless otherwise indicated.
class DownloadService {
 public:
     
	 static  DownloadService * Get();
	 
	 ~DownloadService();
	 
	 void SetBrowser(CefRefPtr<CefBrowser> browser) {
		 this->browser_ = browser;
	 }

	 void PostTask(CefRefPtr<DVideoTask> task);
	 void AddTask(CefString &url);
	 void ReduceTask();

	 void NotifyProgress( int progress, int total);

	 CURL * GetCurl() {
		 return curl_;
	 }

	 bool IsRunning();

	 void  SetCurl(CURL * c) {
		 curl_ = c;
	 }

	 void SetDownloadingPaperid(CefString &paperid) {
		 this->paperid_ = paperid;
	 }

	 void Pause();
	 void Resume();

	 void AddCount();

	 void MinusCount();

	 static int  progress_func(void *p,
		 double t, /* dltotal */
		 double d, /* dlnow */
		 double ultotal,
		 double ulnow);
	 static size_t  getcontentlengthfunc(void *ptr, size_t size, size_t nmemb, void *stream);

	 static int tracefunc(CURL *handle, curl_infotype type,
		 char *data, size_t size,
		 void *userp);

	 static size_t DownloadService::DownloadCallback(void* pBuffer, size_t nSize, size_t nMemByte, void* pParam);

protected:
	DownloadService();
 
private: 
	int  tasknum_;
	CefRefPtr<CefBrowser> browser_;
	CefRefPtr<CefThread> dl_thread_; 
	CURL *curl_;
	CefString paperid_;
	std::mutex mutex_;
	std::vector<CefString> tasklist_;
	CefRefPtr<CefThread> pre_thread_;

	COPYDATASTRUCT MyCDS_;
	bigMYREC rec_;
};

}  // namespace client

#endif  // CEF_TESTS_CEFCLIENT_BROWSER_DOWNLOAD_SERVICE_H_
